<template>
  <div p4 flex flex-col h-full @click="clickOut">
    <ElDialog position-absolute style="background: var(--bg-builtin);" shadow-2 b-rd-1 of-hidden
      v-model="showNewNodeMenu" :append-to-body="true" :show-close="false" :style="{
        top: `${menuY}px`,
        left: `${menuX}px`,
      }">
      <template #header="{ close, titleId, titleClass }">
        <div style="background: var(--bg-builtin-dark);" px2 h="2rem" flex items-center c-white>新步骤</div>
      </template>

      <div
        v-for="(item, index) in Object.values(allNodes)" :key="index"
        @click="newNode(item)"
        cursor-pointer h="2rem" flex items-center px2
        select-none class="menu-item">
        {{ item.title }} {{ item.params ? `(${item.params.map(x => x.title).join(', ')})` : undefined }}
      </div>
    </ElDialog>
    <!-- <VueDraggable ref="el" v-model="list">
      <div v-for="item in list" :key="item.id">
        {{ item.name }}
      </div>
    </VueDraggable> -->
    <VueDraggable ref="el" v-model="graph.nodes" :animation="150" handle=".handle">
      <div v-for="(node, index) in graph.nodes" :key="index" flex items-center mb1>
        <div cursor-grab b-rd-3 h-6 w-6 mr2 style="background: var(--bg-builtin);" c-white class="handle" flex items-center justify-center> {{ index + 1 }}</div>
        <LinearNodeDisplay  :node="node" @delete="removeNode(node)"/>
      </div>
      
    </VueDraggable>
    <div px8 py2>
      <el-button type="primary" plain :icon="Plus" size="large" @click="onContextMenu" style="width: fit-content;">添加一步</el-button>
    </div>
    
  </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import LinearNodeDisplay from './LinearNodeDisplay.vue';
import { ElCard, ElDialog } from 'element-plus';
import { Graph } from '~/models/graph/graph';
import { PNode } from '~/models/graph/Prototype/PNode'
import { INode } from '~/models/graph/node/instance';
import { VueDraggable, type UseDraggableReturn } from 'vue-draggable-plus'
import { AllModules } from '~/models/pyBundles';

// UI
const el = ref<UseDraggableReturn>()

// const oGraph = ref(null as Graph | null)
const props = defineProps<{
  graph: Graph
}>()

const allNodes = lodash.flatten(AllModules.map(x => x.declares))

const showNewNodeMenu = ref(false)
const menuX = ref(0)
const menuY = ref(0)
function onContextMenu(e: MouseEvent) {
  showNewNodeMenu.value = true
  menuX.value = e.clientX
  menuY.value = e.clientY
  e.preventDefault()
  e.stopPropagation()
}
function clickOut() {
  console.log('click out');

  showNewNodeMenu.value = false
}

function newNode(proto: PNode) {
  const node = new INode(proto)
  props.graph.nodes.push(node)
  showNewNodeMenu.value = false
}

function removeNode(node: INode) {
  remove(props.graph.nodesId, x => x === node.id)
}
</script>

<style lang="scss" scoped>
.menu-item {
  &:hover {
    background: #ffffff40;
  }
}
</style>